package de.stefanocke.roo.wicket;

import java.util.HashMap;
import java.util.Map;

import org.springframework.roo.classpath.PhysicalTypeIdentifier;
import org.springframework.roo.classpath.PhysicalTypeIdentifierNamingUtils;
import org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails;
import org.springframework.roo.metadata.MetadataIdentificationUtils;
import org.springframework.roo.model.JavaType;
import org.springframework.roo.project.LogicalPath;

public class MidUtils {
	private String metadataClass;

	private static Map<String, MidUtils> cache = new HashMap<String, MidUtils>();

	public MidUtils(String metadataClass) {
		super();
		this.metadataClass = metadataClass;
	}

	public String getMetadataIdentiferType() {
		return MetadataIdentificationUtils.create(metadataClass);
	}

	public String createIdentifier(JavaType javaType, LogicalPath path) {
		return PhysicalTypeIdentifierNamingUtils.createIdentifier(metadataClass, javaType, path);
	}

	public String createIdentifier(ClassOrInterfaceTypeDetails typeDetails) {
		return createIdentifier(typeDetails.getName(),
				PhysicalTypeIdentifier.getPath(typeDetails.getDeclaredByMetadataId()));
	}

	public JavaType getJavaType(String metadataIdentificationString) {
		return PhysicalTypeIdentifierNamingUtils.getJavaType(metadataClass, metadataIdentificationString);
	}

	public static JavaType getJavaTypeForMid(String mid) {
		return getForMid(mid).getJavaType(mid);
	}

	public LogicalPath getPath(String metadataIdentificationString) {
		return PhysicalTypeIdentifierNamingUtils.getPath(metadataClass, metadataIdentificationString);
	}

	public boolean isValid(String mid) {
		return PhysicalTypeIdentifierNamingUtils.isValid(metadataClass, mid);
	}

	public static MidUtils getForMid(String mid) {
		return get(MetadataIdentificationUtils.getMetadataClass(mid));
	}

	public static MidUtils get(Class<?> metadataClass) {
		return get(metadataClass.getName());
	}

	public static MidUtils get(String metadataClass) {
		MidUtils result = cache.get(metadataClass);
		if (result == null) {
			result = new MidUtils(metadataClass);
			cache.put(metadataClass, result);
		}
		return result;
	}
}
